/*
 * @Author: Quinn
 * @Date: 2023-03-03 15:23:09
 * @LastEditors: quinn
 * @Description:
 */
import axios from 'axios'
import { query2string, jsonToForm, jsonToXXX } from '@/utils/index'
import { localStorageAsync } from '@/utils/public'
import { Message, Notification, MessageBox, Loading } from 'element-ui'
import { LOGIN_PATH } from '@/assets/js/define'
// import Vue from 'vue'

let loadingIns = null
let timer = null
let isDialogVisible = false
const timeout = 60000

const instance = axios.create({
  timeout,
})

const onLoadingConfig = (config) => {
  const { loadingConfig = {}, loadingType = '' } = config
  return {
    ...loadingConfig,
  }
}

const responseSuccess = async (response) => {
  //   this.$nextTick(() => {
  // 以服务的方式调用的 Loading 需要异步关闭
  if (loadingInstance) {
    loadingInstance.close()
  }
  //   })
  const { config = {}, data: res = {} } = response
  const { silence, fit, ignore } = config
  if (ignore) return Promise.resolve(res)

  if ([200].includes(res?.code)) {
    if (config.url.indexOf('new/cad/parse') > -1) {
      if (Array.isArray(res.result.code) && res.result.code.length > 0) {
        if (!isDialogVisible) {
          isDialogVisible = true
          // 使用 Element UI 的 MessageBox 弹出错误信息
          await MessageBox.alert(
            `错误编码: ${res.result.code.join(', ')}`,
            '转化图解析错误',
            {
              confirmButtonText: '关闭',
              type: 'error',
              callback: () => {
                isDialogVisible = false // 重置状态，允许再次弹窗
              },
            }
          )
        }
      }
      if (Array.isArray(res.result.code2) && res.result.code2.length > 0) {
        if (!isDialogVisible) {
          isDialogVisible = true
          await MessageBox.alert(
            `错误编码: ${res.result.code2.join(', ')}`,
            '仓储架图解析错误',
            {
              confirmButtonText: '关闭',
              type: 'error',
              callback: () => {
                isDialogVisible = false
              },
            }
          )
        }
      }
      if (Array.isArray(res.result.code3) && res.result.code3.length > 0) {
        if (!isDialogVisible) {
          isDialogVisible = true
          await MessageBox.alert(
            `错误编码: ${res.result.code3.join(', ')}`,
            '营业区报价图解析错误',
            {
              confirmButtonText: '关闭',
              type: 'error',
              callback: () => {
                isDialogVisible = false
              },
            }
          )
        }
      }
      if (
        res &&
        Array.isArray(res.result?.code4) &&
        res.result.code4.length > 0
      ) {
        if (!isDialogVisible) {
          isDialogVisible = true
          await MessageBox.alert(
            `错误编码: ${res.result.code4.join(', ')}`,
            '仓储报价图解析错误',
            {
              confirmButtonText: '关闭',
              type: 'error',
              callback: () => {
                isDialogVisible = false
              },
            }
          )
        }
      }
      return
    }
    if (typeof fit === 'function') return Promise.resolve(fit(res?.result))
    return Promise.resolve(res?.result)
  } else if ([10043, 10042].includes(res?.code)) {
    window.location.href = LOGIN_PATH
    return Promise.reject(res)
  } else {
    if (!silence) Message.warning(res?.msg || '发生了一些小问题~')
    return Promise.reject(res)
  }
}

const responseFail = async (error) => {
  const { response = {}, config = {}, data: res = {} } = error
  if (response.status == 401) return (window.location.href = LOGIN_PATH)
  if (axios.isAxiosError(error)) console.log(response.status)
  Message.warning(response?.data?.message || `网络错误，请稍后重试！`)
  const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
  if (reg.test(error))
    Message.warning(response?.data?.message || `请稍后重试！`)
  return Promise.reject(error?.response?.status === 500 ? response : error)
}
let loadingInstance = null
const requestSuccess = async (config) => {
  try {
    // console.log('config', config)
    const { url } = config
    const isDownload = await localStorageAsync.getItem('download')
    if (isDownload && url.includes('getZym')) {
      const options = {
        lock: true,
        text: '下载中请勿频繁点击',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      }
      loadingInstance = Loading.service(options)
      // console.log('loading')
    }
  } catch (e) {
    console.log(e)
  }
  return config
}

instance.interceptors.request.use(requestSuccess, (error) => {
  return Promise.reject(error)
})

instance.interceptors.response.use(responseSuccess, responseFail)

export async function post(url, data = {}, config = {}) {
  let { headers = {} } = config
  return instance.post(url, data, {
    ...config,
    headers,
  })
}

export async function postForm(url, data = {}, config = {}) {
  const form = jsonToForm(data)
  console.log(form)
  return instance.post(url, form, {
    ...config,
    headers: {
      ...(config.headers || {}),

      'Content-Type': `multipart/form-data; boundary=${form._boundary}`,
    },
  })
}

export async function postForm2(url, data = {}, config = {}) {
  // const params = jsonToXXX(data);
  const params = data
  return instance.post(url, params, {
    ...config,
    headers: {
      ...(config.headers || {}),
      //  "Content-Type": "application/x-www-form-urlencoded",
      'Content-Type': 'application/json',
    },
  })
}

export async function get(url, data = {}, config = {}) {
  if (data && Object.keys(data).length > 0) {
    url += '?' + query2string(data)
  }
  return instance.get(url, config)
}

export async function deleteFn(url, data = {}, config = {}) {
  if (data && Object.keys(data).length > 0) {
    url += '?' + query2string(data)
  }
  return instance.delete(url, config)
}

export async function patch(url, data = {}, config = {}) {
  return instance.patch(url, data, config)
}

export default { post, postForm, postForm2, get, patch, deleteFn }
